package com.baidu.location;


import android.app.Activity;

import com.xindaoapp.happypet.entry.Location;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 百度定位的管理类
 * 
 * @author Yangqing
 * 
 *         在OnCreate中初始化管理类，在开始定位时，调用startLoacation和InitLocation，在Activity销毁前，调用stopLocation
 *         在IRequest回调需要的数据
 * 
 */
public class BaiDuLocationManager {

    public BDLocationListener myListener = new MyLocationListener();


    private IRequest<Location> request;

    private static BaiDuLocationManager manager = new BaiDuLocationManager();


    private static LocationClient mLocationClient;

    public boolean isLoadFirst = true;


    public static BaiDuLocationManager getInstance(Activity context) {

        if (mLocationClient == null) {
            mLocationClient = new LocationClient(context);
        }
        return manager;
    }

    public void start() {
        mLocationClient.start();
    }

    public void startLoacation(Activity context, IRequest<Location> request) {
        // InitLocation();
        this.request = request;
        mLocationClient.registerLocationListener(myListener); // 注册监听函数
        InitLocation();
        mLocationClient.start();
    }

    public void InitLocation() {

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setProdName("com.xindaoapp.happypet"); // 设置产品线名称
        option.setScanSpan(1000);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);

        // LocationClientOption option = new LocationClientOption();
        // option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
        // option.setCoorType("gcj02");// 返回的定位结果是百度经纬度，默认值gcj02
        // option.setScanSpan(20000);// 设置发起定位请求的间隔时间为5000ms
        // option.setIsNeedAddress(true);
        // mLocationClient.setLocOption(option);
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (isLoadFirst) {
                isLoadFirst = false;
                request.request(new Location(location.getLatitude(), location.getLongitude(), "",
                        location.getAddrStr(), location.getCity()));
            }
        }

        @Override
        public void onReceivePoi(BDLocation arg0) {
            System.out.println(arg0.getAddrStr());
        }



    }

    public void stopLocation() {
        if (mLocationClient != null) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
        }
    }


}
